import { message } from 'antd';
import type { AxiosRequestConfig } from 'axios';
import { service } from './response';

/**
 * 业务层统一拦截：
 * 1. http 状态码异常由 axios 拦截器处理
 * 2. 业务码异常（success=false）在这里统一弹窗
 * 3. 成功时直接返回 payload，调用方只用关心 data 
 */
export function bizRequest<R>(promise: Promise<{ data: API.IResult<R> }>): Promise<R> {
  return promise.then(({ data: res }) => {
    if (!res.success) {
      message.error(res.errorMessage || '请求出错');
      return Promise.reject(res);
    }
    return res.data!;
  });
}

export const http = {
  get: async <R = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<R> => {
    return bizRequest<R>(
      service.get(url, {
        params,
        ...config,
      }),
    );
  },

  post: async <R = any, D = any>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig,
  ): Promise<R> => {
    return bizRequest<R>(service.post(url, data, config));
  },

  put: async <R = any, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise<R> => {
    return bizRequest<R>(service.put(url, data, config));
  },

  delete: async <R = any>(url: string, config?: AxiosRequestConfig): Promise<R> => {
    return bizRequest<R>(service.delete(url, config));
  },
};
